package com.sunchangpeng.wechat.mp.menu;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sunchangpeng.wechat.mp.EndpointProvider;
import com.sunchangpeng.wechat.mp.MpAppSetting;
import com.sunchangpeng.wechat.mp.MpWechatClientFactory;
import com.sunchangpeng.wechat.mp.menu.bean.Menu;
import com.sunchangpeng.wechat.mp.menu.bean.RuleMenu;

public class RuleMenus extends Menus {
    public static RuleMenus with(MpAppSetting appSetting) {
        RuleMenus ruleMenus = new RuleMenus();
        ruleMenus.setWechatClient(MpWechatClientFactory.getInstance().with(appSetting));
        return ruleMenus;
    }

    /**
     * 创建个性化菜单，菜单rule不能为空
     */
    public String createRuleMenu(RuleMenu menu) {
        if (menu.getRule() == null) {
            throw new IllegalArgumentException("个性化菜单rule不能为空.menu: " + menu);
        }

        String url = EndpointProvider.get("url.menu.create.condition");
        String response = wechatClient.getTextWithToken(url, JSON.toJSONString(menu));
        return JSON.parseObject(response).getString("menuid");
    }

    /**
     * 删除个性化菜单
     */
    public void deleteRuleMenu(String menuId) {
        String url = EndpointProvider.get("url.menu.delete.condition");
        wechatClient.getTextWithToken(url, JSON.toJSONString(new JSONObject().fluentPut("menuid", menuId)));
    }

    /**
     * 测试个性化菜单匹配结果
     *
     * @param userId userId可以是粉丝的OpenID，也可以是粉丝的微信号。
     */
    public Menu trymatch(String userId) {
        String url = EndpointProvider.get("url.menu.match");
        String response = wechatClient.getTextWithToken(url, JSON.toJSONString(new JSONObject().fluentPut("user_id", userId)));
        return JSON.parseObject(response, MenuWrapper.class).getMenu();
    }
}
